'''Contains all the functions to get Dell device and warranty information.'''
from json.decoder import JSONDecodeError
import requests
import xmltodict
import PySimpleGUI as sg
from warranty_manager.claim.dell.common import (
    get_access_token, get_error_message
)


def get_url(info_type):
    '''Gets the correct URL for the given warranty information.'''
    return f'https://apigtwb2c.us.dell.com/PROD/sbil/eapi/v5/{info_type}'


def get_warranty_request(info_type, tags, token):
    '''Gets the request object for the specified Warranty API method.'''
    return requests.get(
        url=get_url(info_type),
        params={'servicetags': tags},
        headers={'Authorization': f'Bearer {token}'}
    )


def get_model_name(tags):
    '''
    Gets the model name for the Dell device.

    Parameters
    ----------
    tags : str
        The Dell service tags, separated by commas (up to 100),
        which are the equivalent of a serial number

    Returns
    -------
    str
        The device's model name
    '''
    token = get_access_token('Warranty')

    if token:
        res = get_warranty_request('assets', tags, token)

        try:
            res_json = res.json()
        except JSONDecodeError:
            sg.popup_error(
                get_error_message( xmltodict.parse(res.text) ), title='Error'
            )
        else:
            device_id = res_json[0].get('id')

            if device_id:
                return res_json[0]['productLineDescription']
